var Mongoose = require('mongoose');

var voteSchema = Mongoose.Schema({
    user: {
        type: Mongoose.Schema.ObjectId,
        required: true,
        ref: 'User'
    },
    idea: {
        type: Mongoose.Schema.ObjectId,
        required: true,
        ref: 'Idea'
    },
    voteType: {
        type: String,
        default: ''
    }

}, {timestamps: true});

var Vote = Mongoose.model('Vote', voteSchema);

Vote.createVote = function (newVote, callback) {
    newVote.save(callback);
};

Vote.getAllVotes = function(callback){
    Vote.find({}, callback);
}

Vote.getIdeaVoteCount = function (idea, voteType, callback) {
    Vote.find({
        idea: new Mongoose.Types.ObjectId(idea),
        voteType: voteType
    }).count(callback);
};

Vote.findUserVoteOnIdea = function (user, idea, callback) {
    Vote.findOne({
        $and: [{
            idea: new Mongoose.Types.ObjectId(idea),
            user: new Mongoose.Types.ObjectId(user)
        }]
    }, callback);
};

Vote.getVoteCountByUserId = function (userId, callback) {
    Vote.find({user: new Mongoose.Types.ObjectId(userId)}).count(callback);
};

Vote.removeVote = function (ideaId, userId, voteType, callback) {
    Vote.findOneAndRemove({
        $and: [
            {'idea': Mongoose.Types.ObjectId(ideaId)},
            {'user': Mongoose.Types.ObjectId(userId)},
            {'voteType': voteType}]
    }, callback);
};

Vote.deleteVotesByIdea = function (ideaId, callback) {
    Vote.find(
        {'idea': Mongoose.Types.ObjectId(ideaId)}
    ).remove(callback);
};

module.exports = Vote;
